// package-star/pages/brand-withdraw/index.js
import { ManageTargetInfoUpdateMixins } from '../../../behaviors/page';
import { PACKAGE_STAR_PAGE } from '../../../constants/route';
import { WITHDRAW_TYPE, WITHDRAW_TYPE_TEXT } from '../../../constants/common';
import { navTo, navBack, tipToast, tipSuccess, showLoading, hideLoading } from '../../../common/env';
import { TipDialog } from '../../../common/tip';
import { getSettlementInfo, applyWithdraw } from '../../../api/brd';
let loaded = false;

Page({
    mixins: [ManageTargetInfoUpdateMixins],
    data: {
        settlementInfo: {},
        availableAmount: 0,
        withdrawType: WITHDRAW_TYPE.change,
    },
    onLoad(options) {
    },
    onShow() {
        this._handleGetDetail();
    },
    async _handleGetDetail() {
        !loaded && showLoading('加载中...');
        const settlementInfo = await getSettlementInfo();
        const { withdrawingAmount, availableAmount } = settlementInfo;
        this.setData({
            settlementInfo,
            availableAmount: availableAmount - withdrawingAmount > 0 ? availableAmount - withdrawingAmount : 0,
        });
        if (!loaded) hideLoading(); loaded = true;
    },
    async handleWithdrawApply(e) {
        const amount = e.detail;
        const { withdrawType } = this.data;
        const { accountBank } = this.data.settlementInfo;
        if (!accountBank) {
            tipToast('请添加银行卡');
            return;
        }
        const flag = await applyWithdraw({
            amount,
            remark: WITHDRAW_TYPE_TEXT[withdrawType],
        });
        if (flag) {
            tipSuccess('提现成功');
            navBack();
        }
    },
    handleNavToBankCard(e) {
        const { accountBank } = this.data.settlementInfo;
        if (accountBank) {
            TipDialog({
                title: '确定修改提现银行卡？',
                message: '修改银行卡后，需要审核，请待其生效后再申请提现',
                confirmButtonText: '修改',
                ok() {
                    navTo(PACKAGE_STAR_PAGE['brandWithdrawCard']);
                },
            });
        } else {
            navTo(PACKAGE_STAR_PAGE['brandWithdrawCard']);
        }
    },
})
